package com.controller;

import com.mapper.UserMapper;
import com.message.UserMessage;
import com.model.*;
import com.util.ConstantUtil;
import com.util.EmailUtil;
import com.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
@PropertySource("classpath:message.properties")
public class UserCenterController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserMessage userMessage;

    @Autowired
    private JavaMailSender mailSender;

    private static String  testPhoneMsgCode = "123";

    @Autowired
    private Environment env;
    // inject via application.properties
    @Value("${welcome.message:test}")
    private String message = "Hello World";


    @RequestMapping("/accountsetting")
    public String accountsetting(Map<String, Object> model,HttpSession session) {

        User user = (User) session.getAttribute(ConstantUtil.loginSession);

        model.put("pagename", "accountsetting");
        List<Province> provinceList = userMapper.getProvince();
        String provinceCode="";
        for(Province p:provinceList){
            if(StringUtils.isNotBlank(user.getProvince())){
                if( user.getProvince().equalsIgnoreCase(p.getName())){
                    provinceCode = p.getCode();
                }
            }

        }

        List<City> cityList  = userMapper.getCityByProvinceCode(provinceCode);
        String cityCode ="";
        for(City c:cityList){
            if(StringUtils.isNotBlank(user.getCity())) {
                if (StringUtils.isNotBlank(user.getCity()) & c.getName().equalsIgnoreCase(user.getCity())) {
                    cityCode = c.getCode();
                }
            }
        }
        List<Area> areaList = userMapper.getAeraByCityCode(cityCode);
        model.put("cityList",cityList);
        model.put("areaList",areaList);
        model.put("provinceList", provinceList);
        String birthday[] = user.getBirthday().split("-");

        if(birthday.length==3){
            model.put("userYear", birthday[0]);
            model.put("userMonth", birthday[1]);
            model.put("userDay", birthday[2]);
        }

        model.put("provinceList", userMapper.getProvince());
        return "usercenter";
    }


    @RequestMapping("/getCityAndAreaNames")
    @ResponseBody
    public ResponseMsg getCityAndAreaNames(@RequestParam(required = false) String provinceCode, @RequestParam(required = false) String cityCode) {
        ResponseMsg msg = new ResponseMsg();


        if (StringUtils.isNotBlank(provinceCode)) {
            List<City> cityList = userMapper.getCityByProvinceCode(provinceCode);
            msg.setData(cityList);
        } else {
            List<Area> areaList = userMapper.getAeraByCityCode(cityCode);
            msg.setData(areaList);
        }
        msg.setStatus(ResponseMsg.success);
        return msg;
    }


    @RequestMapping("/updateUserInfo")
    @ResponseBody
    public ResponseMsg updateUserInfo(HttpSession session,HttpServletRequest request) {

        ResponseMsg msg = new ResponseMsg();
        User user = (User) session.getAttribute(ConstantUtil.loginSession);

        String oldpassword = request.getParameter("oldpassword");
        String newpassword = request.getParameter("newpassword");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String msgCode = request.getParameter("msgCode");

        if(StringUtils.isNotBlank(oldpassword) && StringUtils.isNotBlank(newpassword)){
            if(!MD5Util.MD5(oldpassword).equalsIgnoreCase(user.getPassword())){
                msg.setData("原来的密码不正确！");
                return msg;
            }
            user.setPassword(MD5Util.MD5(newpassword));
        }else if(StringUtils.isNotBlank(phone)){

            Object obj = session.getAttribute("msgCode");
            if(obj==null | ((String)obj).equalsIgnoreCase(msgCode)){
                msg.setData("验证码不正确！");
                return msg;
            }
            user.setPhoneStatus(1);
        }else if(StringUtils.isNotBlank(email)){
            Object obj = session.getAttribute("msgCode");
            if(obj==null | !((Integer)obj+"").equalsIgnoreCase(msgCode)){
                msg.setData("验证码不正确！");
                return msg;
            }
            user.setEmailStatus(1);
        } else{
            String userYear = request.getParameter("userYear");
            String userMonth = request.getParameter("userMonth");
            String userDay = request.getParameter("userDay");

            String province = request.getParameter("province");
            String city = request.getParameter("city");
            String area = request.getParameter("area");
            String address = request.getParameter("address");

            user.setBirthday(userYear + "-" + userMonth + "-" + userDay);
            user.setProvince(province);
            user.setCity(city);
            user.setArea(area);
            user.setAddress(address);
        }
        userMapper.updateUserInfo(user);
        msg.setStatus(ResponseMsg.success);
        return msg;
    }

    @RequestMapping("/sendMsgToEmailPhone")
    @ResponseBody
    public ResponseMsg sendMsgToEmailPhone(HttpSession session,@RequestParam(required = true) int msgType,@RequestParam(required = true) String address) {
        ResponseMsg msg = new ResponseMsg();
        User user = (User) session.getAttribute(ConstantUtil.loginSession);
        Random random =new Random();
        int msgCode = random.nextInt(10000);
        session.setAttribute("msgCode",msgCode);

        if(msgType == 1){ //手机

        }else if(msgType == 2){ //邮箱
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("msg@smartplusinc.com");
            message.setTo(address);
            message.setSubject("主题：简单邮件");
            message.setText("您的验证码是：" + msgCode + "。请不要把验证码泄露给其他人。");

            mailSender.send(message);
        }
        msg.setStatus(ResponseMsg.success);
        return msg;
    }

    @RequestMapping("/refreshUserInfo")
    @ResponseBody
    public ResponseMsg refreshUserInfo(HttpSession session) {
        ResponseMsg msg = new ResponseMsg();
        User user = (User) session.getAttribute(ConstantUtil.loginSession);
        List<User> userList = userMapper.getUserByCondition(user);
        if (userList.size() != 1 || (((User) userList.get(0)).getStatus() != 1)) {
            msg.setData("您的账号有问题，请联系客服！");
            return msg;
        }
        User userTemp = userList.get(0);

        msg.setStatus(ResponseMsg.success);
        msg.setData(userTemp);
        return msg;
    }


    @RequestMapping("/reSetPassword")
    @ResponseBody
    public ResponseMsg reSetPassword(@RequestParam(required = true) String oldPassword, @RequestParam(required = true) String newPassword, HttpSession session) {
        ResponseMsg msg = new ResponseMsg();
        User user = (User) session.getAttribute(ConstantUtil.loginSession);
        if(StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)){
            msg.setData("参数不能为空！");
            return msg;
        }

        User tempUser = new User();
        tempUser.setUserId(user.getUserId());
        tempUser.setPassword(MD5Util.MD5(newPassword));
        userMapper.updateUserInfo(tempUser);
        msg.setStatus(ResponseMsg.success);
        return msg;
    }


    @RequestMapping("/forgotpasswordone")
    public String forgotpasswordone() {
        return "forgotpasswordone";
    }

    @RequestMapping("/forgotpasswordtwo")
    public String forgotpasswordtwo() {
        return "forgotpasswordtwo";
    }

    @RequestMapping("/forgotpasswordthree")
    public String forgotpasswordthree() {
        return "forgotpasswordthree";
    }


    @RequestMapping("/updateUserPhoneAndEmailStatus")
    @ResponseBody
    public ResponseMsg updateUserPhoneAndEmailStatus(HttpServletRequest request) {
        String emailStatus = request.getParameter("emailStatus");
        String userId = request.getParameter("userId");
        String phoneStatus = request.getParameter("phoneStatus");
        ResponseMsg msg = new ResponseMsg();
        User user = new User();
        user.setUserId(Integer.parseInt(userId));
        user.setPhoneStatus(Integer.parseInt(phoneStatus));
        user.setEmailStatus(Integer.parseInt(emailStatus));

        userMapper.updateUserInfo(user);

        msg.setStatus(ResponseMsg.success);
        return msg;
    }





    public UserMapper getUserMapper() {
        return userMapper;
    }


    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public UserMessage getUserMessage() {
        return userMessage;
    }

    public void setUserMessage(UserMessage userMessage) {
        this.userMessage = userMessage;
    }

    public Environment getEnv() {
        return env;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    public JavaMailSender getMailSender() {
        return mailSender;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }
}
